
const Metalsmith = require('metalsmith');
const fse = require('fs-extra');
const path = require('path');
const rimraf = require('rimraf');
const Handlebars = require('handlebars');
const inquirer = require('inquirer');
const GetGitUser = require('./git-user');
const package = require('../package.json');
const getOptions = require('./options');
const prompt = require('./prompt');
const filter = require('./filter');
const render = require('./replace');


const templateVersion = package.version;

// register handlebars helper
Handlebars.registerHelper('if_eq', function (a, b, opts) {
    return a === b
        ? opts.fn(this)
        : opts.inverse(this)
});

Handlebars.registerHelper('unless_eq', function (a, b, opts) {
    return a === b
        ? opts.inverse(this)
        : opts.fn(this)
});


const opts = {
    helpers: {
        if_or(v1, v2, options) {
            if (v1 || v2) {
                return options.fn(this)
            }

            return options.inverse(this)
        },
        template_version() {
            return templateVersion
        },
    }
};

opts.helpers && Object.keys(opts.helpers).map(key => {
    Handlebars.registerHelper(key, opts.helpers[key])
});


/**
 * 项目目录名、下载的模板的临时路径、项目目录路径和回调函数
 * @param {*} name 
 * @param {*} src 
 * @param {*} dest 
 * @param {*} done 
 */
function generate(name, src, dest, done) {
    const current_name = path.join(process.cwd(), name);
    // 删除同名项目目录，以便新建项目
    if (fse.existsSync(current_name)) rimraf.sync(current_name);

    let target = path.join(dest, name);
    const opts = getOptions();


    const { prompts } = opts;

    if (fse.existsSync(path.join(src, 'template'))) {
        src = path.join(src, 'template');
    }

    // 1.获取目标文件
    const metalsmith = Metalsmith(src);

    // 2.注入元数据
    metalsmith.metadata({
        destDirName: name,
        inPlace: dest === process.cwd(),
        noEscape: true
    });

    // 3.收集并挂载数据
    metalsmith.use((files, metalsmith, done) => {
        prompt(metalsmith.metadata(), prompts, done);
    });

    // 4.过滤文件 
    metalsmith.use((files, metalsmith, done) => {
        filter(files, {}, metalsmith.metadata(), done);
    });

    // 5.渲染模板 
    metalsmith.use((files, metalsmith, done) => {
        render(files, metalsmith.metadata(), done);
    });

    // 6.清空目标目录并向其拷贝注入文件 
    metalsmith.clean(true)
        .source('.') // 源目录
        .destination(target) // 模板目录
        .build((err, files) => {
            if (err) {
                console.log(`err is: ${err}`);
            } else {
                console.log(`complete success`);
            }
            // 拷贝注入完毕后, 进行npm install、eslint操作

            // if (typeof opts.complete === 'function') {
            //     const helpers = { chalk, logger, files }
            //     opts.complete(data, helpers)
            // } else {
            //     logMessage(opts.completeMessage, data)
            // }
        });

    // done("this is message");
    console.log(target);

}

module.exports = generate;